﻿using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using Ornament.MVCWebFrame.Areas.MemberShips.Models;
using Ornament.MemberShip;
using Ornament.Web;
using Ornament.Web.MemberShips;
using Ornament.Web.Mvc;

namespace Ornament.MVCWebFrame.Areas.Settings.Controllers
{
    [NHibernateFilter]
    public class MemberShipController : Controller
    {
        //
        // GET: /System/MemberShip/

        public ActionResult Index()
        {
            return View(OrnamentMemberShipSetting.GetMemberShipSetting());
        }

        public ActionResult SaveMembershipSetting(OrnamentMemberShipSetting setting)
        {
            OrnamentMemberShipSetting srcSetting = OrnamentMemberShipSetting.GetMemberShipSetting();
            OrnamentMemberShipSetting.Save(setting);

            var privider = (MemberShipProvider) Membership.Provider;

            if (srcSetting.PasswordFormat != setting.PasswordFormat)
            {
                if (srcSetting.PasswordFormat == MembershipPasswordFormat.Hashed)
                {
                    setting.PasswordFormat = MembershipPasswordFormat.Hashed;
                }
                else
                {
                    IQueryable<User> allUsers =
                        from user in OrnamentContext.Current.GetDaoFactory<IMemberShipFactory>().Users select user;

                    foreach (User user in allUsers)
                    {
                        string password = privider.DecodeString(user.Password, srcSetting.PasswordFormat);
                        user.ChangePassword(privider.EncodeString(password, setting.PasswordFormat));
                    }
                }
            }

            //JavaScript("alert('保存成功')");
            return RedirectToAction("Index");
        }
    }
}